import pymysql

class  DbHandle:

    def __init__(self,host='localhost', user='root', password='123456', database='quote',port=3306):
            self.host=host
            self.user=user
            self.password=password
            self.database=database
            self.port = port
            self.charset='utf8mb4' # 使用 utf8mb4 支持全字符集，如 emoji
            self.cursorclass = pymysql.cursors.DictCursor # 返回字典类型的结果


    #创建连接
    def get_connect(self):
        print(self.host,self.user,self.password,self.database,self.port,self.charset)
        connection = pymysql.connect(host=self.host,user=self.user,
                                     password=self.password,database=self.database,
                                     port=self.port,charset=self.charset,cursorclass=self.cursorclass)
        return connection


    #查询语句
    def execute_query(self,query, params=None):
        with self.get_connect().cursor() as cursor:
            if params:
                cursor.execute(query, params)  # 使用参数化查询以防止 SQL 注入
            else:
                cursor.execute(query)
                # 获取所有结果（如果有的话）
            result = cursor.fetchall()
        return result


    def update_query(self,query, params=None):
        connect=self.get_connect()
        with connect.cursor() as cursor:
            if params:
                result = cursor.execute(query, params)# 使用参数化查询以防止 SQL 注入
                connect.commit()
            else:
                result = cursor.execute(query)
        return result

